<template>
  <div class="site-order-container">
    <!-- 通知图标 -->
    <div class="notification-icon" @click="showNotifications = !showNotifications">
      <el-badge :value="notificationCount" :max="99" class="item">
        <i class="el-icon-bell"></i>
      </el-badge>
    </div>

    <!-- 通知面板 -->
    <el-drawer
      title="消息通知"
      :visible.sync="showNotifications"
      direction="rtl"
      size="30%"
    >
      <div class="notification-panel">
        <div class="notification-header">
          <span>未读消息 ({{ notificationCount }})</span>
          <el-button type="text" @click="clearNotifications">清空所有</el-button>
        </div>
        <div class="notification-list">
          <div
            v-for="notification in notifications"
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.read }"
            @click="markNotificationAsRead(notification)"
          >
            <div class="notification-content">
              <div class="notification-title">{{ notification.title }}</div>
              <div class="notification-message">{{ notification.content }}</div>
              <div class="notification-time">{{ notification.time }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>

      <h1>站点订单管理</h1>
      <!-- 查询条件 -->
      <el-form :inline="true" :model="query" class="demo-form-inline">
      <el-form-item label="入库时间区间：">
        <el-date-picker
          v-model="query.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 350px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态：">
        <el-select v-model="query.orderState" placeholder="请选择订单状态" style="width: 200px;">
          <el-option label="全部" :value="null"></el-option>
          <el-option label="已创建" :value="1"></el-option>
          <el-option label="已确认" :value="2"></el-option>
          <el-option label="已接取" :value="3"></el-option>
          <el-option label="待接取" :value="4"></el-option>
          <el-option label="已入库" :value="5"></el-option>
          <el-option label="已取消" :value="6"></el-option>
          <el-option label="待分配" :value="7"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户电话：">
        <el-input v-model="query.userPhone" placeholder="请输入用户电话" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item label="临时工名字：">
        <el-input v-model="query.workName" placeholder="请输入临时工名字" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchOrders">查询</el-button>
      </el-form-item>
    </el-form>
  
      <!-- 订单列表 -->
      <el-table :data="orders" style="width: 100%; margin-bottom: 20px;">
        <el-table-column prop="orderNumber" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="userName" label="用户姓名" width="120"></el-table-column>
        <el-table-column prop="userPhone" label="用户电话" width="150"></el-table-column>
        <el-table-column prop="startTime" label="预约时间" width="180"></el-table-column>
        <el-table-column label="订单状态" width="120">
          <template #default="scope">
            {{ getOrderState(scope.row.orderState) }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="成交金额" width="120"></el-table-column>
        <el-table-column prop="creatTime" label="创建时间" width="180"></el-table-column>
        <el-table-column prop="workName" label="临时工姓名" width="120"></el-table-column>
        <el-table-column label="站点" width="120">
          <template #default="scope">
            {{ getSiteName(scope.row.siteId) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button 
              v-if="scope.row.orderState === 2"
              type="success" 
              size="small" 
              @click="handleConfirmOrder(scope.row)"
            >确认入库</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleCancelOrder(scope.row)"
              v-if="[1, 3, 4, 7].includes(scope.row.orderState)"
            >取消订单</el-button>
            <el-button 
            v-if="scope.row.orderState === 7" 
              type="primary" 
              size="small" 
              @click="handleAssignSite(scope.row)"
            >分配工作人员</el-button>
            <el-button 
            
              type="info" 
              size="small" 
              @click="handleViewDetails(scope.row)"
            >查看详情</el-button>      
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        background
        layout="total, prev, pager, next, sizes"
        :total="total"
        :page-size="query.pageSize"
        :page-sizes="[10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="text-align: right;"
      ></el-pagination>

    <!-- 分配工作人员弹窗 -->
    <el-dialog
      title="分配工作人员"
      :visible.sync="assignDialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <div v-if="workers.length === 0" class="no-workers">
        暂无可用工作人员
      </div>
      <div v-else class="workers-list">
        <div
          v-for="worker in workers"
          :key="worker.adminId"
          class="worker-item"
          @click="confirmAssign(worker)"
        >
          <span>{{ worker.name }}</span>
          <span class="phone">({{ worker.phone }})</span>
        </div>
      </div>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailsDialogVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ currentOrderDetails.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ currentOrderDetails.userName }}</el-descriptions-item>
        <el-descriptions-item label="用户电话">{{ currentOrderDetails.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ currentOrderDetails.startTime }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ getOrderState(currentOrderDetails.orderState) }}</el-descriptions-item>
        <el-descriptions-item label="成交金额">{{ currentOrderDetails.totalAmount }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentOrderDetails.creatTime }}</el-descriptions-item>
        <el-descriptions-item label="临时工姓名">{{ currentOrderDetails.workName }}</el-descriptions-item>
        <el-descriptions-item label="站点名称">{{ currentOrderDetails.siteName }}</el-descriptions-item>
        <el-descriptions-item label="用户地址" :span="2">{{ currentOrderDetails.userAddress }}</el-descriptions-item>
      </el-descriptions>

      <div class="waste-details" >
        <h3 style="margin: 20px 0;">废品详情</h3>
        <el-table 
          v-if="currentOrderDetails.wasteList && currentOrderDetails.wasteList.length > 0"
          :data="currentOrderDetails.wasteList" 
          style="width: 100%"
          border
        >
          <el-table-column prop="wasteInfo" label="废品简介" min-width="120">
            <template slot-scope="scope">
              {{ scope.row.wasteInfo || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="数量" width="100">
            <template slot-scope="scope">
              {{ scope.row.weight || '-' }} {{ scope.row.unit || '' }}
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.sastePrice || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="总价" width="100">
            <template slot-scope="scope">
              ¥{{ scope.row.sasteAllPrice || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="废品类型" width="120">
            <template slot-scope="scope">
              {{ getWasteTypeName(scope.row.sasteTypeId) || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="图片" width="120">
            <template slot-scope="scope">
              <el-image 
                v-if="scope.row.wasteImage"
                style="width: 60px; height: 60px; object-fit: cover;"
                :src="scope.row.wasteImage"
                :preview-src-list="[scope.row.wasteImage]">
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-data" style="text-align: center; padding: 20px; color: #909399;">
          暂无废品信息
        </div>
      </div>
    </el-dialog>
    </div>
  </template>

  <script>
  import axios from 'axios';
import { webSocketClient } from '../utils/websocket';
  
  export default {
    data() {
      return {
        query: {
          dateRange: [],
          siteId: null, // 站点 ID
          siteName: '', // 站点名称（用于显示）
          orderState: 7, // 订单状态
          userPhone: '', // 用户电话
          workName: '', // 临时工名字
          pageNum: 1, // 当前页码
          pageSize: 10, // 每页条数
        },
        orders: [], // 订单数据
        siteOptions: [], // 站点列表
        total: 0, // 总条数
        wasteTypes: [], // 添加废品类型列表
      adminInfo: { // 添加管理员信息对象
        name: '',
        phone: '',
        role: 0,
        siteId: null,
        username: ''
      },
      workers: [], // 工作人员列表
      assignDialogVisible: false, // 分配弹窗显示状态
      currentOrder: null, // 当前操作的订单
      notifications: [], // 存储通知消息
      notificationCount: 0, // 未读通知数量
      showNotifications: false, // 控制通知面板的显示状态
      siteMap: {}, // 添加站点映射对象
      detailsDialogVisible: false,
      currentOrderDetails: {
        orderNumber: '',
        userName: '',
        userPhone: '',
        startTime: '',
        orderState: null,
        totalAmount: '',
        creatTime: '',
        workName: '',
        siteName: '',
        userAddress: '',
        wasteList: []
      },
      };
    },
    methods: {
    // 获取管理员个人信息
    fetchAdminInfo() {
      return new Promise((resolve, reject) => {
        axios
          .get('/zsd-permission/admin-info/selAdminInfo')
          .then((response) => {
            if (response.data.code === null) {
              this.adminInfo = response.data.data;
              // 将站点ID设置到查询条件中
              this.query.siteId = this.adminInfo.siteId;
              // 获取个人信息后自动查询订单
              this.fetchOrders();
              resolve(this.adminInfo);
            } else {
              this.$message.error('获取个人信息失败：' + response.data.msg);
              reject(new Error(response.data.msg));
            }
          })
          .catch((error) => {
            console.error('获取个人信息出错：', error);
            this.$message.error('获取个人信息出错，请稍后再试');
            reject(error);
          });
      });
    },

      // 获取订单数据
      fetchOrders() {
        const { dateRange, ...restQuery } = this.query;
        const params = {
          ...restQuery,
          startTime: dateRange && dateRange[0] ? dateRange[0] : null,
          endTime: dateRange && dateRange[1] ? dateRange[1] : null,
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize,
          siteId: this.adminInfo.siteId // 确保带上站点ID
        };

        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (params[key] === null || params[key] === undefined || params[key] === '') {
            delete params[key];
          }
        });

        axios
          .get('/zsd-order/order-info/findAllOrder', { params })
          .then((response) => {
            if (response.data.code === 200) {
              const pageData = response.data.data;
              this.orders = pageData.records || []; // 设置订单数据
              this.total = pageData.total || 0; // 设置总条数
            } else {
              this.$message.error('查询失败：' + response.data.msg);
            }
          })
          .catch((error) => {
            console.error('请求出错：', error);
            this.$message.error('请求出错，请稍后再试');
          });
      },
  
      // 取消订单
      handleCancelOrder(row) {
        this.$prompt('请输入取消原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空',
        })
          .then(({ value }) => {
            const params = {
              orderNumber: row.orderNumber,
              remarks: value,
            };
  
            axios
              .put('/zsd-order/order-info/cancelOrder', params)
              .then((response) => {
                if (response.data.code === 200) {
                  this.$message.success('订单取消成功');
                  this.fetchOrders(); // 刷新订单列表
                } else {
                  this.$message.error('取消失败：' + response.data.msg);
                }
              })
              .catch((error) => {
                console.error('请求出错：', error);
                this.$message.error('请求出错，请稍后再试');
              });
          })
          .catch(() => {
            this.$message.info('已取消操作');
          });
      },
  
      // 获取订单状态的中文描述
      getOrderState(state) {
        const stateMap = {
          1: '已创建',
          2: '已确认',
          3: '已接取',
          4: '待接取',
          5: '已入库',
          6: '已取消',
          7: '待分配',
        };
        return stateMap[state] || '未知状态';
      },
  
      // 切换每页条数
      handleSizeChange(size) {
        this.query.pageSize = size;
        this.fetchOrders();
      },
  
      // 切换页码
      handleCurrentChange(page) {
        this.query.pageNum = page;
        this.fetchOrders();
      },

    // 获取工作人员列表
    fetchWorkers() {
      const params = {
        role: 3, // 临时工角色
        state: '1', // 空闲状态
        siteId: this.adminInfo.siteId, // 当前站点
        pageSize: 100 // 获取足够多的数据
      };

      axios
        .get('/zsd-permission/admin-info/selAdminInfoById', { params })
        .then((response) => {
          if (response.data.code === null) {
            this.workers = response.data.data.list;
          } else {
            this.$message.error('获取工作人员列表失败：' + response.data.msg);
          }
        })
        .catch((error) => {
          console.error('获取工作人员列表出错：', error);
          this.$message.error('获取工作人员列表出错，请稍后再试');
        });
    },

    // 分配工作人员
    handleAssignSite(row) {
      if (row.orderState !== 7) {
        this.$message.warning('只能分配待分配的订单');
        return;
      }
      this.currentOrder = row;
      this.fetchWorkers();
      this.assignDialogVisible = true;
    },

    // 确认分配工作人员
    confirmAssign(worker) {
      if (!this.currentOrder) return;

      const params = {
        orderNumber: this.currentOrder.orderNumber,
        workId: worker.adminId
      };

      axios
        .put('/zsd-order/order-info/siteAllocationOrder', params)
        .then((response) => {
          if (response.data.code === 200) {
            this.$message.success('分配成功');
            this.assignDialogVisible = false;
            this.fetchOrders(); // 刷新订单列表
          } else {
            this.$message.error('分配失败：' + response.data.msg);
          }
        })
        .catch((error) => {
          console.error('分配出错：', error);
          this.$message.error('分配出错，请稍后再试');
        });
    },

    // 处理WebSocket消息
    handleWebSocketMessage(message) {
      // 如果是纯文本消息
      if (message.type === 'text') {
        this.notifications.unshift({
          id: Date.now(),
          type: 'info',
          title: '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: '新消息',
          message: message.content,
          type: 'info',
          duration: 5000,
          position: 'top-right'
        });
      } else {
        // 处理其他类型的消息
        this.notifications.unshift({
          id: Date.now(),
          type: message.type || 'info',
          title: message.title || '新消息',
          content: message.content,
          time: new Date().toLocaleTimeString(),
          read: false
        });
        this.notificationCount++;
        
        // 显示通知
        this.$notify({
          title: message.title || '新消息',
          message: message.content,
          type: message.type || 'info',
          duration: 5000,
          position: 'top-right'
        });
      }
    },

    // 标记通知为已读
    markNotificationAsRead(notification) {
      notification.read = true;
      this.notificationCount = this.notifications.filter(n => !n.read).length;
    },

    // 清除所有通知
    clearNotifications() {
      this.notifications = [];
      this.notificationCount = 0;
    },

    // 确认废品入库
    handleConfirmOrder(row) {
      this.$confirm('确认要将该订单标记为已入库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          orderNumber: row.orderNumber
        };

        axios
          .put('/zsd-order/order-info/siteUpdateOrder', null, { params })
          .then((response) => {
            if (response.data.code === 200) {
              this.$message.success('确认入库成功');
              this.fetchOrders(); // 刷新订单列表
            } else {
              this.$message.error('确认入库失败：' + response.data.msg);
            }
          })
          .catch((error) => {
            console.error('确认入库出错：', error);
            this.$message.error('确认入库出错，请稍后再试');
          });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },

    // 获取站点名称
    getSiteName(siteId) {
      return this.siteMap[siteId] || siteId;
    },

    // 获取站点列表并创建映射
    async fetchSites() {
      try {
        const response = await axios.get('/zsd-merchant/site/list', {
          params: {
            pageNum: 1,
            pageSize: 100
          }
        });
        if (response.data.code === 200) {
          const sites = response.data.data.records;
          // 创建站点映射
          this.siteMap = sites.reduce((map, site) => {
            map[site.id] = site.siteName;
            return map;
          }, {});
        } else {
          console.error('获取站点列表失败:', response.data.msg);
        }
      } catch (error) {
        console.error('请求站点列表出错:', error);
      }
    },

    // 获取废品类型列表
    fetchWasteTypes() {
      axios
        .get("/zsd-waste/waste-type/selWasteType")
        .then((response) => {
          if (response.data.code === 200) {
            this.wasteTypes = response.data.data || [];
          } else {
            this.$message.error("获取废品类型失败：" + response.data.msg);
          }
        })
        .catch((error) => {
          console.error("请求出错：", error);
          this.$message.error("请求出错，请稍后再试");
        });
    },

    // 获取废品类型名称
    getWasteTypeName(typeId) {
      if (!typeId) return '-';
      const type = this.wasteTypes.find(t => t.id === typeId);
      return type ? type.wasteTypeName : typeId;
    },

    // 查看订单详情
    async handleViewDetails(row) {
      // 重置当前订单详情
      this.currentOrderDetails = {
        orderNumber: '',
        userName: '',
        userPhone: '',
        startTime: '',
        orderState: null,
        totalAmount: '',
        creatTime: '',
        workName: '',
        siteName: '',
        userAddress: '',
        wasteList: []
      };
      
      // 显示对话框
      this.detailsDialogVisible = true;
      
      try {
        // 先设置基本信息
        Object.keys(row).forEach(key => {
          this.$set(this.currentOrderDetails, key, row[key]);
        });

        // 获取废品详情
        const wasteResponse = await axios.get('/zsd-order/order-waste/findOrderInfo', {
          params: { orderNumber: row.orderNumber }
        });
        
        if (wasteResponse.data.code === 200 && wasteResponse.data.data) {
          // 确保 wasteList 是数组
          const wasteList = Array.isArray(wasteResponse.data.data) ? wasteResponse.data.data : [wasteResponse.data.data];
          this.$set(this.currentOrderDetails, 'wasteList', wasteList);
          console.log('废品列表已更新:', this.currentOrderDetails.wasteList);
        }

        // 获取站点详情
        if (row.siteId) {
          const siteResponse = await axios.get('/zsd-merchant/site/find/id', {
            params: { id: row.siteId }
          });
          if (siteResponse.data.code === 200) {
            this.$set(this.currentOrderDetails, 'siteName', siteResponse.data.data.siteName);
          }
        }

        // 获取用户地址详情
        if (row.userAddress) {
          const addressResponse = await axios.get('/zsd-user/user-address/selUserAddressById', {
            params: { id: row.userAddress }
          });
          if (addressResponse.data.code === 200) {
            this.$set(this.currentOrderDetails, 'userAddress', addressResponse.data.data.address);
          }
        }
      } catch (error) {
        console.error('获取订单详情出错:', error);
        this.$message.error('获取订单详情失败');
      }
    },
  },
  mounted() {
    // 获取token并连接WebSocket
    const loginUser = JSON.parse(localStorage.getItem('loginUser'));
    if (loginUser && loginUser.token) {
      // 先获取管理员信息，然后再连接WebSocket
      this.fetchAdminInfo()
        .then(adminInfo => {
          if (adminInfo.siteId) {
            // 确保之前的连接已关闭
            if (webSocketClient.ws) {
              webSocketClient.close();
            }
            // 使用站点ID和token建立新连接
            webSocketClient.connect(loginUser.token, adminInfo.siteId);
            webSocketClient.addMessageHandler(this.handleWebSocketMessage);
            // 获取站点信息
            this.fetchSites();
            // 获取废品类型信息
            this.fetchWasteTypes();
          } else {
            console.error('站点ID不存在，无法建立WebSocket连接');
          }
        })
        .catch(error => {
          console.error('初始化失败：', error);
        });
    }
  },
  beforeDestroy() {
    // 组件销毁前移除消息处理器
    webSocketClient.removeMessageHandler(this.handleWebSocketMessage);
  }
  };
  </script>

<style scoped>
.site-order-container {
  padding: 20px;
}

.workers-list {
  max-height: 300px;
  overflow-y: auto;
}

.worker-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.3s;
}

.worker-item:hover {
  background-color: #f5f7fa;
}

.worker-item .phone {
  color: #909399;
  margin-left: 10px;
}

.no-workers {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.notification-icon {
  position: fixed;
  top: 20px;
  right: 20px;
  cursor: pointer;
  z-index: 1000;
}

.notification-icon i {
  font-size: 24px;
  color: #606266;
}

.notification-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.notification-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #f0f9eb;
}

.notification-title {
  font-weight: bold;
  margin-bottom: 5px;
}

.notification-message {
  color: #606266;
  margin-bottom: 5px;
}

.notification-time {
  font-size: 12px;
  color: #909399;
}
</style>